package com.javabi.unix.delimited;

import com.javabi.unix.line.LineNumberProcessor;

public abstract class DelimitedLineProcessor<R> extends LineNumberProcessor<R> {

	private final String delimiter;

	protected DelimitedLineProcessor(String delimiter) {
		if (delimiter == null) {
			throw new NullPointerException("delimiter");
		}
		this.delimiter = delimiter;
	}

	@Override
	protected boolean skipEmptyLines() {
		return true;
	}

	@Override
	protected boolean trimLines() {
		return true;
	}

	protected boolean trimKey() {
		return true;
	}

	protected boolean trimValue() {
		return true;
	}

	@Override
	public boolean processLine(String line, int number) {
		int index = line.indexOf(delimiter);
		if (index == -1) {
			throw new IllegalArgumentException("line: '" + line + "' does not contain delimiter: '" + delimiter + "'");
		}

		String key = line.substring(0, index);
		String value = line.substring(index + 1);
		if (trimKey()) {
			key = key.trim();
		}
		if (trimValue()) {
			value = value.trim();
		}
		return processLine(key, value, number);
	}

	public abstract boolean processLine(String key, String value, int number);

}
